package net.vinote.sosa.rpc.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import net.vinote.sosa.rpc.RpcConstant;
import net.vinote.sosa.rpc.Session;
import net.vinote.sosa.rpc.process.MessageReceiver;

/**
 * 接受业务消息
 * 
 * @author Seer
 * @version RpcClientHandler.java, v 0.1 2015年11月22日 下午3:01:00 Seer Exp.
 */
public class RpcChannelHandler<T> extends ChannelHandlerAdapter {
	private MessageReceiver<T> receiver;

	public RpcChannelHandler(MessageReceiver<T> receiver) {
		this.receiver = receiver;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
		AttributeKey<Session> sessionKey = AttributeKey.valueOf(RpcConstant.SESSION_KEY);
		receiver.receive(ctx.attr(sessionKey).get(), (T) msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
}